<template>
  <a-modal
    width="600px"
    v-model:visible="visible"
    :title="`${record?.nickname ?? '群成员'}（${memberLength}）`"
    hide-cancel
    :footer="null"
  >
    <div class="flex flex-a-c w-full mb-20">
      <a-input-search
        allow-clear
        size="large"
        placeholder="输入群成员名称检索"
        v-model="searchValue"
      />
    </div>
    <a-table
      :columns="columns"
      :data="tableData"
      :show-header="false"
      row-key="Wxid"
      :bordered="false"
      :pagination="false"
      :loading="loading"
      :scroll="{ y: '400px' }"
    >
      <template #memberInfo="{ rowIndex, record }">
        <div class="flex flex-a-c">
          <div class="w-30 mr-20 flex flex-j-c">{{ rowIndex + 1 }}</div>
          <a-image
            width="42"
            height="42"
            class="mx-4"
            :preview="false"
            style="border-radius: 4px"
            :src="record.avatar"
          />
          <span class="ml-16">{{ record.nickname }}</span>
        </div>
      </template>
    </a-table>
  </a-modal>
</template>

<script setup>
import { reactive } from 'vue'

const { ipcRenderer } = window.electron
const visible = ref(false)
const loading = ref(false)
const searchValue = ref()
const tableDataO = reactive([])
const memberLength = ref(0)
const record = ref()
const columns = [
  {
    title: '群成员',
    slotName: 'memberInfo',
    width: 100
  }
]

// 监听群成员列表消息
ipcRenderer.on('recvWxGroupMember', (event, message) => {
  const memberList = message?.member_list ?? []
  tableDataO.splice(0, tableDataO.length, ...memberList)
  memberLength.value = message?.total ?? 0
  if (loading.value) {
    loading.value = false
  }
})

// 打开编辑框并回显表单值
const openMemberModal = (recordO) => {
  visible.value = true
  if (record.value && record.value.wxid === recordO.wxid) return
  loading.value = true
  record.value = recordO
  let groupTime = null
  ipcRenderer.send('getWxGroupMember', recordO.wxid)
  groupTime = setTimeout(() => {
    loading.value = false
    clearTimeout(groupTime)
    groupTime = null
  }, 3000)
}

const tableData = computed(() => {
  if (searchValue.value) {
    return tableDataO.filter((item) => item.nickname.includes(searchValue.value))
  } else {
    return tableDataO.slice() // 使用 slice() 创建 tableDataO 的浅拷贝
  }
})
defineExpose({ openMemberModal })
</script>
